<template>
  <el-dialog
    v-model="visible"
    :title="titleMap[mode]"
    :width="1024"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <sc-water-mark ref="wm" text="已审核" :color="'rgba(128,128,128,0.1)'">
      <el-form
        :model="form"
        :rules="rules"
        ref="dialogForm1"
        label-width="70px"
        label-position="top"
        class="formhead"
      >
        <el-row style="display: flex; align-items: center">
          <el-col :span="15">
            <span style="font-size: 25px">销售订单</span>
          </el-col>
          <el-col :span="3">
            <el-form-item label="编号" prop="code" class="backgroudBlue">
              <el-input
                label="编号"
                v-model="form.code"
                readonly
                placeholder="自动生成"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="单据日期" prop="billdate" class="backgroudGreen">
              <el-date-picker
                v-model="form.billdate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="交期" prop="delivery_date" class="backgroudBlue">
              <el-date-picker
                v-model="form.delivery_date"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- <sc-water-mark ref="wm" text="已审核" subtext="誉卓纱线"> -->
      <sk-tabs type="border-card">
        <el-tab-pane ref="tab" label="基础信息">
          <el-form
            :model="form"
            :rules="rules"
            ref="dialogForm"
            label-width="70px"
            label-position="right"
          >
            <el-row>
              <el-col :span="15">
                <el-row>
                  <el-col :span="8" align="客户">
                    <el-form-item label="客户" prop="customer_id">
                      <skAutoChoose
                        v-model="form.customer.name"
                        :params="[
                          {
                            name: {
                              type: 'nlr',
                              value: 'YZ',
                            },
                          },
                        ]"
                        :name="'customer'"
                        :assign="form"
                        @select="cunstomerSelect"
                      >
                      </skAutoChoose>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" align="联系人">
                    <el-form-item label="联系人" prop="linkman_id" class="addicon">
                      <el-select v-model="form.linkman_id" :placeholder="'先选择客户'">
                        <el-option
                          v-for="item in linkmanList"
                          :value="item.id"
                          :label="item.name + ',' + item.phone"
                          :key="item.name + ',' + item.phone"
                        >
                        </el-option>
                      </el-select>
                      <el-button
                        type="info"
                        icon="ElIconPlus"
                        @click="linkmanAdd"
                        style="width: 22px; height: 24px"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="理单人" prop="singler_id">
                      <el-input v-model="form.singler.name" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="工艺线路" prop="process_route_id">
                      <skDicSelect
                        v-model="form.process_route_id"
                        :code="'process_route'"
                        :editsource="'default'"
                        :placeholder="'请选择工艺'"
                      >
                      </skDicSelect>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="投缸比" prop="feeding_ratio">
                      <el-input
                        v-model="form.feeding_ratio"
                        clearable
                        :placeholder="'请填投缸比'"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="烘干包重" prop="hg_weight">
                      <skDicSelect
                        v-model="form.hg_weight"
                        :code="'HgWeight'"
                        :placeholder="'选择烘干包重'"
                      >
                      </skDicSelect>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="订单要求" prop="remark">
                      <el-input v-model="form.remark" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :span="8">
										<el-form-item
											label="倒毛要求"
											prop="dmremark"
										>
											<el-input
												v-model="form.dmremark"
												clearable
											></el-input>
										</el-form-item>
									</el-col> -->
                  <el-col :span="8">
                    <el-form-item label="是否含税" prop="tax_id">
                      <el-switch
                        v-model="form.tax_id"
                        active-value="1"
                        inactive-value="0"
                      ></el-switch>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="是否出口" prop="is_export">
                      <el-radio-group v-model="form.is_export">
                        <el-radio-button label="0">是</el-radio-button>
                        <el-radio-button label="1">否</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="5" :offset="3">
                <el-row>
                  <el-form-item label="欠款" prop="code">
                    <el-input label="账户剩余" v-model="ARBalance" clearable></el-input>
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item label="额度" prop="code">
                    <el-input
                      label="客户额度"
                      v-model="credit_limit"
                      clearable
                    ></el-input>
                  </el-form-item>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
          <el-divider content-position="left">订单明细</el-divider>
          <sc-VxeTable
            ref="save"
            :gridEvts="gridEvts"
            :data="form.details"
            :gridOps="gridOps"
            :height="300"
            @cellClick="cellClick"
            :tablecode="'market_order_sale'"
          >
          </sc-VxeTable>
        </el-tab-pane>
        <el-tab-pane label="附件">
          <sk-upload
            v-model="form.attachments"
            :limit="10"
            draggable
            tip="单个文件不要超过10M,请上传图像格式文件"
          >
          </sk-upload>
        </el-tab-pane>
      </sk-tabs>
    </sc-water-mark>
    <!-- </sc-water-mark> -->
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        type="primary"
        v-if="form.status_id == 0"
        :loading="isSaveing"
        @click="submit()"
        >保 存</el-button
      >
    </template>
  </el-dialog>
  <linkman-add ref="saveDialog" @success="handleSuccess"> </linkman-add>
</template>

<script>
import linkmanAdd from "./linkmanAdd";
import skDicSelect from "@/components/skDicSelect";
import skAutoChoose from "@/components/skAutoChoose";
import XEUtils from "xe-utils";
export default {
  emits: ["success", "closed"],
  components: { skAutoChoose, skDicSelect, linkmanAdd },
  data() {
    return {
      mode: "add",
      dialog: { save: false },

      ARBalance: 0,
      credit_limit: 0,
      gridEvts: {},
      titleMap: {
        add: "新增",
        edit: "编辑",
      },
      linkmanList: [],
      form: {
        id: "",
        state_id: 2,
        status_id: 0,
        feeding_ratio: 940,
        customer_id: "",
        customer: { name: "" },
        linkman: { name: "" },
        salesman_id: 0,
        linkman_id: "",
        hg_weight: "25",
        process_route_id: "2",
        singler: { name: "" },
        department_id: 0,
        singler_id: 0,
        billdate: XEUtils.toDateString(new Date(), "yyyy-MM-dd"),
        code: "",
        remark: "",
        details: [],
        attachments: [],
      },
      rules: {
        billdate: { required: true, message: "请选择单据日期" },
        customer_id: { required: true, message: "请选择客户" },
        linkman_id: { required: true, message: "请选择联系人" },
        process_route_id: { required: true, message: "请选择工艺线路" },
        feeding_ratio: { required: true, message: "投缸比必填" },
        hg_weight: { required: true, message: "烘干标准必填" },
        // delivery_date: { required: true, message: "交期必填" },
      },
      visible: false,
      isSaveing: false,
      gridOps: {
        height: 300,
        columns: [
          {
            field: "material.name",
            event: {
              select: ({ e, row }) => {
                row["material"]["spec"] = e.spec;
              },
            },
          },
          {
            field: "auxiliary_quantity",
            event: {
              keyup: ({ row }) => {
                row["quantity"] = row["auxiliary_quantity"] * 25;
              },
            },
          },
          {
            field: "price",
            event: {
              keyup: ({ row }) => {
                row["amount"] = row["quantity"] * row["price"];
              },
            },
          },
          {
            field: "amount",
            event: {
              keyup: ({ row }) => {
                row["price"] = row["amount"] / row["quantity"];
              },
            },
          },
          {
            field: "color.name",
            event: {
              select: ({ e, row }) => {
                row["color"] = e;
              },
            },
          },
        ],
      },
    };
  },
  watch: {},
  mounted() {
    let userInfo = this.$TOOL.data.get("USER_INFO");
    this.form.singler.name = userInfo.username;
    this.form.singler_id = userInfo.id;
    this.form.department_id = userInfo.department_id;
    this.form.linkman = { name: userInfo.username, phone: userInfo.phone };
  },
  methods: {
    cellClick(data) {
      console.log(data ?? "");
    },
    linkmanAdd() {
      this.$refs.dialogForm.validateField("customer_id", (err) => {
        if (err) {
          this.$refs.saveDialog
            .setData(this.form.customer.name, this.form.customer_id)
            .open("add");
        }
      });
    },
    cunstomerSelect(data) {
      this.linkmanList = data.link_mans ?? [];
      this.credit_limit = data.credit_limit;
      this.ARBalance = data.ARBalance;
      this.form.salesman_id = data.salesman_id;
      this.form.linkman_id = this.linkmanList[0]?.id;
      if (data.employee) {
        this.form.singler = data.employee;
        this.form.singler_id = data.employee_id;
      }
    },
    //显示
    open(mode = "add") {
      this.mode = mode;

      this.visible = true;
      this.$nextTick(() => {
        if (this.form.status_id == 1) {
          this.$refs.wm.create();
        } else {
          this.$refs.wm.clear();
        }
      });
      return this;
    },
    handleSuccess(data) {
      this.linkmanList.push(data);
      this.form.linkman_id = data.id;
    },
    //表单提交方法
    submit() {
      this.$refs.dialogForm1.validate((valid) => {
        if (valid)
          this.$refs.dialogForm.validate(async (valid) => {
            if (valid) {
              this.isSaveing = true;

              var res = await this.$API.market.order.save.post(this.form);
              this.isSaveing = false;
              if (res.code == 200) {
                this.$emit("success", this.form, this.mode);
                this.visible = false;
                this.$message.success("操作成功");
              }
            }
          });
      });
    },
    async getItems(id) {
      var res = await this.$API.market.order.details.get({
        filter: [{ main_id: id }],
      });
      if (res.code == 200) {
        this.form.details = res.data.rows;
      }
    },
    async getLinkMan(id) {
      var res = await this.$API.basedata.businessCompany.linkmanGet.get({
        filter: [{ company_id: id }],
      });
      if (res.code == 200) {
        this.linkmanList = res.data;
        if (this.linkmanList.length == 0) {
          let userInfo = this.$TOOL.data.get("USER_INFO");
          this.linkmanList.push({
            id: "key",
            name: userInfo.username,
            phone: userInfo.phone,
          });
        }
        if (this.form.linkman_id == "key") this.form.linkman_id = this.linkmanList[0].id;
      }
    },
    //表单注入数据
    async setData(data) {
      for (let i in data) {
        if (data[i] === null) delete data[i];
      }
      delete data.details;
      Object.assign(this.form, data);

      await this.getLinkMan(this.form.customer_id);
      await this.getItems(this.form.id);
    },
  },
};
</script>

<style>
.addicon .el-select {
  width: calc(100% - 24px);
}

.addicon .el-input__wrapper {
  border-top-right-radius: 0px;
  border-bottom-right-radius: 0px;
}

.addicon .el-button--small {
  border-top-left-radius: 0px;
  border-bottom-left-radius: 0px;
}
</style>
